package com.jplus.framework.mvc.handler;

import java.util.LinkedHashMap;
import java.util.Map;

import com.jplus.framework.mvc.ActionHandle;
import com.jplus.framework.mvc.action.Handler;
import com.jplus.framework.mvc.action.Requester;

/**
 * 默认处理器映射[单例]
 *
 * @author huangyong
 * @author Yuanqy
 */
public class HandlerMapping {
	/**
	 * 单例模式，要考虑线程安全
	 */
	private ThreadLocal<Map<String, String>> restful = new ThreadLocal<Map<String, String>>();

	/**
	 * 获取Action对应的处理类
	 */
	public Handler getHandler(String currentRequestMethod, String currentRequestPath) {
		Map<Requester, Handler> actionMap = ActionHandle.getActionMap();
		Requester requester;
		for (Map.Entry<Requester, Handler> actionEntry : actionMap.entrySet()) {
			requester = actionEntry.getKey();
			if (requester.getRequestMethod().equalsIgnoreCase(currentRequestMethod) && matching(requester.getRequestPath(), currentRequestPath)) {
				Handler h = actionEntry.getValue();
				h.setRequestRestful(restful.get());
				return h;
			}
		}
		return null;
	}

	/**
	 * 匹配restful
	 */
	private boolean matching(String rp, String crp) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		String[] rps = rp.split("\\/");
		String[] crps = crp.split("\\/");
		if (rps.length != crps.length)
			return false;
		for (int i = 0; i < rps.length; i++) {
			if (rps[i].startsWith("{") && rps[i].endsWith("}")) {
				map.put(rps[i].substring(1, rps[i].length() - 1), crps[i]);
				continue;
			} else if (rps[i].equals(crps[i])) {
				continue;
			} else {
				map = null;
				return false;
			}
		}
		restful.set(map);
		return true;
	}
}
